package com.schooleducation.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.schooleducation.entity.User;
import com.schooleducation.service.ServiceFactory;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/login")
public class LoginController {

	@Resource(name = "serviceFac")
	private ServiceFactory serviceFac;

	/*
	 * 获取登录页面
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String getLoginPage() {

		return "login";
	}

	/**
	 * 提交登录数据
	 * 
	 * @param data
	 * @param session
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public String doLogin(String data, HttpSession session) {
		User u = (User) JSONObject.toBean(JSONObject.fromObject(data), User.class);
		User user = serviceFac.getUserService().doLogin(u);
		Map<String, Object> state = new HashMap<String, Object>();
		if (user == null) {
			state.put("message", "fail");
		} else {
			state.put("message", "success");
			switch (user.getUserRoles().getRolesName()) {
			case "学生":
				session.setAttribute("user", user);
				state.put("page", "index");
				break;
			case "教师":
				session.setAttribute("teacher", user);
				state.put("page", "teacher");
				break;
			case "管理员":
				session.setAttribute("admin", user);
				state.put("page", "admin");
				break;
			}
		}

		return JSONObject.fromObject(state).toString();
	}

	/**
	 * 注销登陆
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "logout", method = RequestMethod.POST)
	@ResponseBody
	public String doLogout(HttpSession session, String type) {

		if (type == null) {
			session.removeAttribute("user");
		} else {
			if (type.equals("admin")) {
				session.removeAttribute("admin");
			} else if (type.equals("teacher")) {
				session.removeAttribute("teacher");
			}
		}

		return null;
	}
}
